package com.dreammakerteam.frameworkdemo.base.utils;

import com.dreammakerteam.frameworkdemo.base.domain.DBaseException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Random;

/**
 * 文件
 */
public class FileUtil {
    public static final String TEMPPATH;
    static {
        // 创建临时文件夹
        File temp = new File(ResourceUtil.APP.get("app.files.temp", "temp"));
        if (!temp.exists() && !temp.mkdirs())
            throw new DBaseException("无法创建临时文件夹");
        TEMPPATH = temp.getAbsolutePath() + "/";
    }

    /**
     * 获取上传文件
     * @param multipartFile 文件
     * @return 真实的file对象
     */
    public static File[] uploadFiles(MultipartFile[] multipartFile) {
        try {
            File[] files = new File[multipartFile.length];
            for (int i = 0; i < multipartFile.length; i++) {
                if (multipartFile[i].getSize() == 0)
                    continue;

                // 创建目标对象
                File file = new File(TEMPPATH + multipartFile[i].getOriginalFilename());

                if (!file.exists() && !file.createNewFile())
                    throw new DBaseException("无法上传文件");

                // 上传文件
                multipartFile[i].transferTo(file);

                files[i] = file;
            }
            return files;
        } catch (DBaseException e) {
            throw e;
        } catch (Exception e) {
            throw new DBaseException("未知异常");
        }
    }


    public String getRandomFileName() {




        return null;
    }
}
